package HW2_1.Firefox;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.support.ui.Select;


public class a_login_password {
	private WebDriver driver;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();
	
	
	
	@Before
	public void setUp() throws Exception {
		
		 ProfilesIni allProfiles = new ProfilesIni(); 
	     FirefoxProfile profile = allProfiles.getProfile("default"); 
	     driver = new FirefoxDriver(profile); 
	     
		baseUrl = "http://localhost/tools/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	
	
	@Test
	public void test_login() throws Exception {
		GoToMainPage();
		loginAs("admin", "admin");
		LogOut();
	}
	
	@Test
	public void testEmailChange() {
		GoToMainPage();
		loginAs("admin", "admin");
		goToUserProfile();
		changeEmailTo ("admin@admin.ru");
		goToUserProfile();
		changeEmailTo ("admin@admin.com");
		LogOut();
	}
	
	
	

	private void changeEmailTo(String email) {
		driver.findElement(By.id("email")).clear();
		driver.findElement(By.id("email")).sendKeys(email);
		driver.findElement(By.name("submit")).click();
		
	}

	

	private void goToUserProfile() {
		driver.findElement(By.linkText("My profile")).click();
	
	}





	private void LogOut() {
		driver.findElement(By.linkText("Log out")).click();
		driver.switchTo().alert().accept();
	}

	
	
	private void loginAs(String userName, String password) {
		driver.findElement(By.id("username")).clear();
		driver.findElement(By.id("username")).sendKeys(userName);
		driver.findElement(By.name("password")).clear();
		driver.findElement(By.name("password")).sendKeys(password);
		driver.findElement(By.name("submit")).click();
	}
	
	

	private void GoToMainPage() {
		driver.get(baseUrl + "PHP4DVD");
	}

	
	
	@After
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
}
